﻿using Shop.BLL;
using Shop.Models;
using Shop.Models.DTO;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Shop.MVC.Controllers
{
    public class OrderController : Controller
    {
        BaseManager<Address> addressManager = new BaseManager<Address>();
        OrderManager ordersManager = new OrderManager();
        // 确认订单页面
        public ActionResult Confirm()
        {
            var user = Session["User"] as Users;
            if (user == null)
                return RedirectToAction("Login", "account");

            // 读取收获地址
            var where = "userid=@uid";
            SqlParameter[] sp = { new SqlParameter("@uid", user.Id) };
            var list= addressManager.GetList(where, sp);
            var address=list.FirstOrDefault(x=>x.IsDefault==true);
            if (address == null)
            {
                address = list.FirstOrDefault();
            }
            if (address == null)
            {
                address = new Address();
            }
            ViewBag.Address = address;

            return View();
        }

        [HttpPost]
        public ActionResult CreateAddress(Address model)
        {
            if (ModelState.IsValid)
            {
                var user = Session["user"] as Users;
                model.UserId = user.Id;
                addressManager.Add(model);
                return Json(new { success = true, msg = "添加成功！" });
            }
            return Json(new { success = false, msg = "验证失败！" });
        }

        /// <summary>
        /// 下单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CreateOrder(OrderPostDto model)
        {
            // 设置明细的
            var user = Session["user"] as Users;
            model.UserId = user.Id;
            // 需要向订单表和订单明细保存数据，注意，这是事务的
            var oid= new OrderManager().SaveOrder(model);
            if (oid > 0)
            {
                return Json(new { success = true, msg = "成功！" ,data= oid });
            }
            return Json(new { success = false, msg = "服务器错误！" });
        }

        //支付页面
        public ActionResult Pay(int id)
        {
            ViewBag.OrderId = id;
            return View();
        }

        // 确认支付
        public ActionResult ConfirmPay(int id)
        {
            ordersManager.ChangeOrderState(id, 1);
            return Content("<script>alert('支付成功');location='/home/index';</script>");
        }
    }
}